﻿/// <reference path="vswd-ext_2.2.js" />
Ext.Ajax.timeout = 12000;
var ROOT_IMG_URL = "Content/images/";
function addDays(fromtime, days) {
    var newdate = new Date();
    var newtimems = fromtime.getTime() + (days * 24 * 60 * 60 * 1000);
    newdate.setTime(newtimems);
    return newdate;
}

Ext.Window.prototype.addTaskButton = function(button) {
    this.taskButton = button;
}

function addTaskButtonForWindow(win) {
    if (!win.taskButton) {
        var button = new Ext.Toolbar.Button({
            text: win.title,
            iconCls: win.iconCls,
            listeners: {
                'click': function() {
                    if (win.hidden)
                        win.show();
                    else
                        win.hide();
                }
            }
        });
        maintoolbar.addButton(button);
        maintoolbar.doLayout();
        win.addTaskButton(button);
        win.on('close', function() {
            maintoolbar.remove(win.taskButton);
            win.taskButton.destroy();
        });
    }
    win.hide(win.taskButton.getEl());
}




function getExtjsTimeFormatByClientLanguage() {
    var r = 'Y-m-d';
    var cl = window.navigator.language;
    if (cl == null)
        cl = window.navigator.userLanguage;
    cl = cl.toLowerCase();
    if (cl.indexOf('zh') == 0) {
        //chinese language
        if (cl == 'zh-cn')
            r = 'Y-m-d';
        else if (cl == 'zh-hk')
            r = 'd/m/Y';
        else if (cl == 'zh-tw')
            r = 'Y/m/d';
    }
    else if (cl.indexOf('en') == 0) {
        if (cl == 'en-us' || cl == "en-ph" || cl == "en" || cl == "en-zw")
            r = 'm/d/Y';
        else if (cl == 'en-za')
            r = 'Y/m/d';
        else
            r = 'd/m/Y';
    }
    else if (cl.indexOf('es') == 0) {
        r = 'd/m/Y';
    }
    else if (cl.indexOf('de') == 0) {
        r = 'd.m.Y';
    }
    else if (cl.indexOf('fr') == 0) {
        r = 'd/m/Y';
    }
    return r;
}



var imap;
//var ibmap


var panelmenu = new Ext.Panel({
    id: 'panelmenu',
    layout: 'anchor',
    title: '',
    region: 'north',
    height: 30,
    split: false,
    items: [pheader, maintoolbar]
});


var paneldevice = new Ext.Panel({
    layout: 'fit',
    title: _TrackerMain_Device,
    region: 'center',
    collapsible: false,
    split: true,
    autoScroll: false,
    //autoScroll : false,
    defaults: { autoScroll: false },
    items: [grddevice],
    tbar: devtoolbar
});



var pheight = getCookie("pcmdheight") == null ? 320 : parseInt(getCookie("pcmdheight"));

var panelcommand = new Ext.Panel({
    id: 'panelcommand',
    layout: 'form',
    border: false,
    title: _TrackerMain_Command,
    region: 'south',
    collapsible: true,

    split: true,
    height: pheight,
    items: [panelallcommand]

});

panelcommand.addListener('resize', function(obj, adjWidth, adjHeight, rawWidth, rawHeight) {
    setCookie('pcmdheight', panelcommand.getHeight().toString(), 365);
    setCookie('pcmdwidth', panelcommand.getWidth().toString(), 365);
    panelparams.setHeight(panelcommand.getHeight()-200);
    
});
panelcommand.setVisible(false);
var paneleast = new Ext.Panel({
    id: 'paneleast',
    title: _TrackerMain_ControlPanel,
    region: 'west',
    width: 380,
    collapsible: true,
    split: true, 
    collapseMode: 'mini',
    layout: 'border',
    defaults: { autoScroll: false },
    items: [paneldevice,panelcommand]
});


var imap = new TrackerMap(); 
var newMap = imap.mapPanel;
var tablemapandpanorama = new Ext.Panel({
    id: 'tablemapandpanorama',
    layout: 'border',
    region: 'center',
    header: false,
    border: false,
    items: [newMap],
    listeners: {
        resize: function() {
           // panelmap.checkResize();
        }
    }
});
// Update all tracker position in map
var delta = 0;
window.setInterval(function(){
	Ext.Ajax.request({
		url : 'HandlerLastLocation',
		success : function (response, opts) {
			var lstDevice = Ext.decode(response.responseText);
			if(lstDevice != null){								
				for(var i = 0, len= lstDevice.length; i<len; i++){
					//only test post						
						//delta += 0.0001;
						//lstDevice[i].latitude = (parseFloat(lstDevice[i].latitude)+delta)+"";
						//lstDevice[i].longitude = (parseFloat(lstDevice[i].longitude)+delta)+"";						
					//
					var trackerinfo = new TrackerInfo(lstDevice[i]);					
					imap.updatePosition(trackerinfo);
				}				
			}

		}
	});
},11000);//103000

var panelinfotab = new Ext.TabPanel({
    id: 'panelinfotab',
    region: 'south',
    split: true,
    height: 215,
    collapsible: true,
    collapseMode: 'mini',
    activeTab: 0,
    //items: [panelstatus, panelalarms, panelinfo]
    items: [panelstatus, panelalarms]
});

var panelcenter = new Ext.Panel({
    id: 'panelcenter',
    title: '',
    region: 'center',
    layout: 'border',
    split: true,
    items: [tablemapandpanorama,panelinfotab]
});



function createMap(gmap, smallcontrol, fncallback, mapurl, start, stop, con, hasearth, gpanorama) {
    var tmpmap;
    if (meimaptype == 0)
        tmpmap = new MSGMap(gmap, smallcontrol, fncallback, mapurl, start, stop, con, hasearth, gpanorama);
    else if(meimaptype == 1)
        tmpmap = new MSBMap(gmap, smallcontrol, fncallback, mapurl);
    else if (meimaptype == 2)
        tmpmap = new MSMMap(gmap);
    else if (meimaptype == 3 )
        tmpmap = new MSGMapV3(gmap,smallcontrol,fncallback,mapurl);
    else if (meimaptype == 4)
		tmpmap = new MSQMap(gmap, smallcontrol, fncallback, mapurl);
    return tmpmap;
}

Ext.onReady(function() {
    Ext.BLANK_IMAGE_URL = 'Content/images/s.gif'
    Ext.QuickTips.init(); //show quick tips
    soundManager = new SoundManager();
    //soundManager.waitForWindowLoad = true;
    //是否打开调试模式，打开话对viewport有一定影响
    soundManager.debugMode = false;
    //这个是soundManager提供的swf文件所在的文件夹
    soundManager.url = 'sound/swf';
    soundManager.beginDelayedInit();
    soundManager.onload = function() {

        //信息音
        soundManager.createSound({
            id: 'systemSound',
            url: 'sound/mp3/msg.mp3'
            //volume: 100
        });
        //	            //加入音
        soundManager.createSound({
            id: 'alarmSound',
            url: 'sound/mp3/alarm.mp3'
            //volume: 100
        });
        soundLoaded = true;
    }

    // Ext.Ajax.request({
        // url: 'HandlerGetPermission?' + Math.random(),
        // method: 'get',
        // success: function(btn) {
            // var val = btn.responseText;
            // var tt = val.split('|');
            // permission = tt[0];
            // grouplogin = tt[1];
            // //            if (parseInt(permission) < 1 && hidedemopermissionmodel) {
            // //                //                menuadmin.setVisible(false);
            // //                panelcommand.setVisible(false);
            // //                paneleast.doLayout();
            // //            }
            // if (parseInt(permission) > 0) {
                // panelcommand.setVisible(false);
                // paneleast.doLayout();
            // }
            // else {
                // menuOTA.setVisible(false);
                // menuExtSensorDefine.setVisible(false);
                // menuTrackerDefine.setVisible(false);
                // menuRFID.setVisible(false);
                // menudriver.setVisible(false);
                // menuPolygonDefine.setVisible(false);
                // menuPolygonRelationDefine.setVisible(false);
                // menuLEDSettings.setVisible(false);
                // menuFuelSensorDefine.setVisible(false);
                // if (!hidedemopermissionmodel) {
                    // panelcommand.setVisible(true);
                    // paneleast.doLayout();
                // }
            // }
        // }
    // });

    if (showSMS == true) {
        var day = new Date();
        var today = day.getFullYear() + '-' + (day.getMonth() + 1) + '-' + day.getDate();
        var nowtime = "23:59";
        Ext.Ajax.request({
            url: 'HandlerSearchAllSMS',
            method: 'post',
            params: {
                ids: "",
                fromtime: '2001-01-01 00:00:00',
                totime: today + " " + nowtime,
                start: 0,
                limit: 1,
                inout: -1
            },
            success: function(btn) {
                var val = Ext.decode(btn.responseText);
                if (val.data.length > 0) {
                    maintoolbar.addItem({
                        icon: 'images/lightbulb.png',
                        tooltip: { text: val.data[0].sms_content, autoHide: true },
                        handler: function() {
                            smsReportWindow(true);
                            this.destroy();
                        }
                    });
                    maintoolbar.doLayout();
                }
            }
        });
    }

    var view = new Ext.Viewport({
        enableTabScroll: true,
        layout: 'border',
        items: [panelmenu, paneleast, panelcenter]
    });


    // imap = createMap(panelmap.getMap(), false, null, gmapurl, null, null, null, true, panelmap.getPanoramaPanel());
    // if (meimaptype == 0) {
        // if (onlyshowselecteddevice)
            // imap.setCenter(new GLatLng(0, 0), 5);
        // else
            // imap.setCenter(new GLatLng(0, 0), 14);
    // }
    // else if (meimaptype == 1)
        // imap.setCenter(new VELatLong(0, 0), 2, VEMapStyle.Road);
    // else if (meimaptype == 2) {
        // imap.setCenterAndZoom(125, 25, 13);
    // }
    // else if (meimaptype == 3) {
        // if (onlyshowselecteddevice)
            // imap.setCenterbyLatLng(0, 0, 5);
        // else
            // imap.setCenterbyLatLng(0, 0, 14);
    // }
    // else if (meimaptype == 4) {
        // imap.setCenterbyLatLng(0, 0, 5);
    // }
    // imap._latitude = _TrackerMain_Latitude;
    // imap._longitude = _TrackerMain_Longitude;
    // if (showroutemodel) {
        // imap.setRouteCap(_RouteResources_Confirm, _RouteResources_Cancel, _RouteResources_Far, _RouteResources_Close, _RouteResources_EditAll);
    // }
    devicestore.load();

    var autoshowpoi = getCookie("showallpoi") == 'false' ? false : true;
    var showpoiinter = null;


    // function showpoifunction() {
        // if (autoshowpoi) {
            // if (meimaptype == 0) {
                // if (imap.earthState == EnumEarthState.Done || imap.earthState == EnumEarthState.Unknown || imap.earthState == EnumEarthState.Undone) {
                    // showPOI("");
                    // if (showpoiinter) {
                        // clearInterval(showpoiinter);
                        // showpoiinter = null;
                    // }
                // }
                // else {
                    // if (!showpoiinter) {
                        // showpoiinter = setInterval(showpoifunction, 1000);
                    // }
                // }
            // } else {
                // if (!showpoiinter) {
                    // showpoiinter = setInterval(showpoifunction, 1000);
                // }
            // }

        // }

    // }
    // showpoifunction();

    //    panelmap.map.addListener('resize', function() {
    //        imap.checkResize();
    //    });

    setTimeout(function() {
        Ext.get('loading').remove();
        Ext.get('loading-mask').fadeOut({ remove: true });
        Ext.get('header').show();
    }, 1000);

    setInterval(function() {
        if (soundLoaded && (!turnoffalarmsound)) {
            //is has sound function
            hasEmergency = getHasEmergencyStatus();

            if (hasEmergency) {
                soundManager.play('alarmSound');
            }
        }
    }, 15000);


    Ext.Ajax.request({
        url: 'HandlerShowTemperatureAlarm',
        method: 'post',
        success: function(v) {
            if (v.responseText == 'True') {
                setTimeout(function() {
                    if (g_ExtSensorWindowObject == null) {
                        Ext.Ajax.request({
                            url: 'HandlerHasSensorFullOrNoName',
                            method: 'post',
                            success: function(s) {
                                var responseText = s.responseText;
                                if (responseText != "") {
                                    var tmp = responseText.split(',');
                                    var sssids = tmp[0].split('|');
                                    var i;
                                    var tt = "";
                                    for (i = 0; i < sssids.length; i++) {

                                        devicestore.each(function(record) {
                                            if (record.get('sssid') == sssids[i]) {
                                                tt += (tt.length == 0 ? "" : ",") + record.get('trackername');

                                            }
                                        });
                                    }
                                    if (tt.length > 0)
                                        tt += _Message_TemperatureSensorFull;
                                    sssids = tmp[1].split('|');
                                    var aa = "";
                                    for (i = 0; i < sssids.length; i++) {
                                        devicestore.each(function(record) {
                                            if (record.get('sssid') == sssids[i]) {
                                                aa += (aa.length == 0 ? "" : ",") + record.get('trackername');
                                            }
                                        });
                                    }
                                    if (aa.length > 0)
                                        tt += aa + _Message_NoNameSensor;
                                    if (tt.length > 0) {
                                        trackerExtendSensorWin(true);
                                        Ext.MessageBox.show({
                                            title: "",
                                            msg: tt,
                                            buttons: Ext.MessageBox.OK
                                        });
                                    }
                                }
                            }
                        });
                    }
                }, 60000);
            }

        },
        failure: function() {
            Ext.MessageBox.hide();
        }
    });
});

window.onbeforeunload = onbeforeunload_handler;  
window.onunload = onunload_handler;  
function onbeforeunload_handler(){  
    
}  
  
function onunload_handler(){  
    // Ext.Ajax.request({
        // url: 'HandlerLogout',
        // method: 'post',
        // success: function() {
            // window.location.href = "login.aspx";
        // }
    // }); 
}  


